/**
 * Copyright 2010-present Facebook.
 *
 * Licensed under the Apache License, Version 2.0 (the "License");
 * you may not use this file except in compliance with the License.
 * You may obtain a copy of the License at
 *
 *    http://www.apache.org/licenses/LICENSE-2.0
 *
 * Unless required by applicable law or agreed to in writing, software
 * distributed under the License is distributed on an "AS IS" BASIS,
 * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
 * See the License for the specific language governing permissions and
 * limitations under the License.
 */

package com.twodstar.selfie;

import android.app.Activity;
import android.app.AlertDialog;
import android.app.ProgressDialog;
import android.content.Context;
import android.content.DialogInterface;
import android.content.Intent;
import android.database.Cursor;
import android.graphics.BitmapFactory;
import android.net.Uri;
import android.os.AsyncTask;
import android.os.Bundle;
import android.os.Environment;
import android.provider.MediaStore;
import android.support.v4.app.Fragment;
import android.util.Pair;
import android.view.LayoutInflater;
import android.view.View;
import android.view.ViewGroup;
import android.view.Window;
import android.view.WindowManager;
import android.widget.*;
import com.actionbarsherlock.app.SherlockFragment;
import com.facebook.FacebookException;
import com.facebook.FacebookRequestError;
import com.facebook.HttpMethod;
import com.facebook.Request;
import com.facebook.RequestBatch;
import com.facebook.Response;
import com.facebook.Session;
import com.facebook.SessionState;
import com.facebook.internal.Utility;
import com.facebook.model.*;
import com.facebook.widget.ActivityPicker;
import com.facebook.widget.ProfilePictureView;
import com.facebook.widget.WebDialog;
import com.parse.ParseFacebookUtils;
import com.parse.ParseUser;
import org.json.JSONArray;
import org.json.JSONException;
import org.json.JSONObject;
import java.io.*;
import java.util.ArrayList;
import java.util.List;
import com.twodstar.selfie.R;

/**
 * Fragment that represents the main selection screen for Scrumptious.
 */
public class Fragment_NewBattle extends SherlockFragment 
{

	private static Fragment_NewBattle m_Inst;    

    private static final String PENDING_ANNOUNCE_KEY = "pendingAnnounce";
    private static final int REAUTH_ACTIVITY_CODE = 100;
    private static final String PERMISSION = "publish_actions";

    private Button m_BtnStartBattle;
    private ListView listView;
    private ProgressDialog progressDialog;
    private List<Element_BaseList> listElements;
    private ProfilePictureView profilePictureView;
    private TextView userNameView;
    private boolean pendingAnnounce;    
    private Uri m_photoUri;
    private BattleInfo m_BT_Info;
    
    private TextView m_TxtLevel;   
    private TextView m_TxtBattle;
    private PhotoListElement m_PhotoElement;
    private PeopleListElement m_PeopleElement;    
    private Pair<File, Integer> fileAndMinDimemsion;
    private boolean m_IsCallingMakeMeRequest = false;
    
    class BattleInfo
    {
    	 // player 1 
    	public String Player_ID1;
    	public String Player_ID2;
    	public String PlayerName_P1;
    	public String PlayerName_P2;
    	
    	public String 	PhotoID_P1;
    	public String 	PhotoID_P2;    
    	

     };
     
     public void SetPhotoRUI(Uri pURI)
     {
    	 m_photoUri = pURI;
    	 PBUtility.LOG("SetPhotoRUI 1");
    	 if(m_PhotoElement != null)
    	 {    		
    		 PBUtility.LOG("SetPhotoRUI 2");
    		 m_PhotoElement.setPhotoText();
    		 
    	 }
    	 else
    	 {
    		 PBUtility.LOG("SetPhotoRUI 3");
    	 }
     }
     
     
     public void CustomSaveInstanceState(Bundle outState)
     {
    	 if(m_photoUri != null)
     	{
     		outState.putParcelable("photoUri", m_photoUri);
     	}
     }
     
     public void CustomRestoreInstanceState(Bundle outState)
     {
    	 m_photoUri = (Uri)outState.getParcelable("photoUri");
     }
     
  
     public void Reset()
     {
    	 if(profilePictureView != null)
    		 profilePictureView.setProfileId(null);
    	 
    	 if(userNameView != null)
    		 userNameView.setText("");    	 
    	 
    	 if(getActivity()!=null)
    	 {
    		 ((MainActivity)getActivity()).Reset();
    	 }
     }
     
     public static void Recreated()
     {
    	 m_Inst = null;
     }
     
     public static Fragment_NewBattle Instance()
     {
    	 if(m_Inst == null )
    		 m_Inst = new Fragment_NewBattle();
    		 
    	 return m_Inst;
     }

    
    
   
    
    public Fragment_NewBattle()
    {
    	super();
    	m_BT_Info = new BattleInfo();
    	m_BT_Info.PhotoID_P1 = "";
    	m_BT_Info.PhotoID_P2 = "";
    	m_BT_Info.Player_ID1 = "";
    	m_BT_Info.Player_ID2 = "";
    	m_BT_Info.PlayerName_P1 = "";
    	m_BT_Info.PlayerName_P2 = "";
    
    }
    

    @Override
    public void onResume() 
    {
    	
    	if(getActivity() != null)
    	{
    		((MainActivity)getActivity()).SetLocale();
    	}
    	
        super.onResume();        
    }
    
    @Override
    public void onCreate(Bundle savedInstanceState) 
    {
    	if(getActivity() != null)
    	{
    		((MainActivity)getActivity()).SetLocale();
    	}
    	// TODO Auto-generated method stub
    	super.onCreate(savedInstanceState);
    }

    @Override
    public View onCreateView(LayoutInflater inflater, ViewGroup container, Bundle savedInstanceState) 
    {
    	
        super.onCreateView(inflater, container, savedInstanceState);
        View view = inflater.inflate(R.layout.selection, container, false);

        profilePictureView = (ProfilePictureView) view.findViewById(R.id.profilepic);
        profilePictureView.setCropped(true);
        userNameView = (TextView) view.findViewById(R.id.selection_user_name);
        m_BtnStartBattle = (Button) view.findViewById(R.id.ID_BTNStartBattle);
        listView = (ListView) view.findViewById(R.id.selection_list);
        
        m_TxtLevel = (TextView) view.findViewById(R.id.txtLevel);        
        m_TxtBattle = (TextView) view.findViewById(R.id.txtBattle);       
        

        m_BtnStartBattle.setOnClickListener(new View.OnClickListener() 
        {
            @Override
            public void onClick(View view) 
            {
            	//DataManager.SendPush("1006028668", "Battle Now!");
            	
            	//WantToBringAllies();
            	
            	
            	if(SelfieBattleApplication.Instance().isOnline())
            	{            		
            		handleAnnounce();
            	}
            	else if(getActivity() != null)
            	{
            		String text = getString(R.string.check_internet);
        	        Toast toast = Toast.makeText(getActivity(), text, Toast.LENGTH_SHORT);
        	        toast.show();
            	        
            	}
            	
            	
            }
        });

        init(savedInstanceState);

        return view;
    }
    
    public void Tick()
    {
    	if(getActivity() == null)
    		return;
    }
    
    
    public void ShowPlayerInfo()
    {    	
    	ParseUser PU = ParseUser.getCurrentUser();
    	if(PU == null)
    		return;   	
    	
    	Fragment F = ((MainActivity)getActivity()).GetActiveFragment();
    	
    	if(F == null)
    		return;
    	
    
    	if(F instanceof Fragment_NewBattle)
    	{}else
    	{
    		return;
    	}
    	  	    	
		if(m_TxtLevel != null)
    	{
			int Level = SelfieBattleApplication.Instance().CalculateLevel( PU.getInt("BattleWin"));
			if(Level == 0)
				Level = 1;
			String text = "Level: " + Level;			
    		
    		SelfieBattleApplication app = SelfieBattleApplication.Instance();
    		text = text + " ( " + app.GetPlayerTitle(PU) + " ) "; 
    		m_TxtLevel.setText(text);
    	}									       	
    	    	
    	if(m_TxtBattle != null)
    	{
    		m_TxtBattle.setText("Battles: " + PU.getInt("BattleWin") + "/" + PU.getInt("TotalBattle"));
    	}   	
       
    }
    
    
          

    @Override
    public void onActivityResult(int requestCode, int resultCode, Intent data) 
    {
        super.onActivityResult(requestCode, resultCode, data);
        if (resultCode == Activity.RESULT_OK && requestCode >= 0 && requestCode < listElements.size()) 
        {
            listElements.get(requestCode).onActivityResult(data);
        } 
       
    }

    @Override
    public void onSaveInstanceState(Bundle bundle)
    {
        super.onSaveInstanceState(bundle);
        for (Element_BaseList listElement : listElements) 
        {
            listElement.onSaveInstanceState(bundle);
        }
        bundle.putBoolean(PENDING_ANNOUNCE_KEY, pendingAnnounce);
        
    }

    /**
     * Notifies that the session token has been updated.
     */
    private void tokenUpdated() 
    {
        if (pendingAnnounce) 
        {
            UploadPhotoToFB();
        }
    }

    public void onSessionStateChange(final Session session, SessionState state, Exception exception) 
    {
        if (session != null && session.isOpened()) 
        {
            if (state.equals(SessionState.OPENED_TOKEN_UPDATED)) 
            {
                tokenUpdated();
            } 
            else 
            {
                makeMeRequest(session);
            }
        } 
        else 
        {
            
        }
    }
    
    public void makeMeRequest(final Session session)
    {   
    	if(m_IsCallingMakeMeRequest)
    		return;
    	
    	m_IsCallingMakeMeRequest = true;
    	
    	 PBUtility.LOG("makeMeRequest !!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!");
    	    	
    	 if(ParseUser.getCurrentUser() != null )
    	 {
			 if( ParseUser.getCurrentUser().get("FBID") == null || ParseUser.getCurrentUser().getString("FBID").isEmpty() ) 
			 {
				// we need to get FBID  
			 }
			 else
			 {
				 if( profilePictureView != null )    		 
				 {		
		    		 if(profilePictureView.getProfileId() != null)
		    		 {
		    			 PBUtility.LOG("Already got it! " + profilePictureView.getProfileId());
		    			 return;
		    		 }
				 }
		    	 
				 if (session != null && session.isOpened())
				 {}
				 else
				 {
					 PBUtility.LOG("Session is not opened to make request me!");
					 
					 SelfieBattleApplication.Instance().LogoutUser();
					 if(getActivity() != null)
						 ((MainActivity) getActivity()).showFragment(MainActivity.SPLASH);
             		
					 return;
				 }    	 
				 
			 }
    	 }    	 
		
    	
    	String fqlQuery = "SELECT uid,name, current_location.city, current_location.country  FROM user WHERE uid = me()";
        Bundle params = new Bundle();
        params.putString("q", fqlQuery);

        Request request = new Request(session, 
            "/fql", 
            params, 
            HttpMethod.GET, 
            new Request.Callback()
        { 
                public void onCompleted(Response response) 
                {      
                	m_IsCallingMakeMeRequest = false;
                	
                	if(response.getError() != null && getActivity() != null)
                	{
                		SelfieBattleApplication.Instance().LogoutUser();
                		
                		PBUtility.LOG("you need to re log in!");
                		if(getActivity() != null)
                			((MainActivity) getActivity()).showFragment(MainActivity.SPLASH);
                		return;
                	}
                	 GraphObject graphObject = response.getGraphObject();	               
	               	 
	               	 if (graphObject != null) 
	               	 {
	                        JSONObject jsonObject = graphObject.getInnerJSONObject();
	                        
	                        try 
	                        {
	                            JSONArray array = jsonObject.getJSONArray("data");
	                            for (int i = 0; i < array.length(); i++) 
	                            {
	                                JSONObject object = (JSONObject) array.get(i);	                               
	                                
	                                if(i == 0)
	                                {
	                                	if(progressDialog != null)
	                                	{
	                                		progressDialog.dismiss();
	                                		progressDialog = null;
	                                	}
	                                	
	                                	String FBID = object.get("uid").toString();
	                                	String Name = object.get("name").toString();
	                                	
	                                		                                	
	                                	JSONObject LocObject = null;
	                                	if (!object.isNull("current_location")) 
	                                	{
	                                		LocObject = object.getJSONObject("current_location");
	                                	}	                                	 
	                                	
	                                	String City = "";
	                                	String Country = "";
	                                	if(LocObject != null)
	                                	{
	                                		City = LocObject.getString("city");
	                                		Country = LocObject.getString("country");
	                                	}
	                                	
	                                	if(profilePictureView != null)
	                                		profilePictureView.setProfileId(FBID);
	                                	SelfieBattleApplication app = SelfieBattleApplication.Instance();
	                                	app.SetFBID(FBID);
	                                	app.SetName(Name);
	                                	
	                                	if(userNameView != null)
	                                		userNameView.setText(Name);
	                                    
	                                    ParseUser PU = ParseUser.getCurrentUser();                      
	                                    if(PU != null)		
	                                    {
	                                    	if(PU.getString("FBID") == null )		// newly created user? 
	                                    	{
			                                   DataManager.InitNewParseUser(PU, FBID, Name, City, Country);			                                    
	                                    	}
	                                    	else
	                                    	{
	                                    		if(PU.getString("FBID").equalsIgnoreCase(FBID) == false)
	                                    		{
	                                    			// another user 
	                                    			// log out and ask to relog in
	                                    			
	                                    			SelfieBattleApplication.Instance().LogoutUser();
	                                        		
	                                        		PBUtility.LOG("you need to re log in!");
	                                        		if(getActivity() != null)
	                                        			((MainActivity) getActivity()).showFragment(MainActivity.SPLASH);
	                                        		return;
	                                    		}
	                                    	}
	                                    }
	                                    
	                                    
	                                    // change to myanmar font instantly?
	                                    if(getActivity() != null)
	                                    {
	                                    	((MainActivity) getActivity()).SetLocale();	   
	                                    	Fragment_NewBattle.Instance().init(null);
	                                    }
	                                    
	                                }         
	                            }
	                       } 
	                       catch (JSONException e) 
	                       {
	                    	   PBUtility.LOG("shit happened while getting me! " + e.getMessage());
	                    	   e.printStackTrace();
	                       }
		         	       
	                }
                }
                
        });
        
        Request.executeBatchAsync(request);
        if(getActivity() != null)
        	progressDialog = ProgressDialog.show(getActivity(), "",  getActivity().getResources().getString(R.string.loading), true);
    }
    

    /**
     * Resets the view to the initial defaults.
     */
    private void init(Bundle savedInstanceState) 
    {
    	

        listElements = new ArrayList<Element_BaseList>();

        //listElements.add(new EatListElement(0));
        //listElements.add(new LocationListElement(1));
        
        m_PeopleElement = new PeopleListElement(0);
        listElements.add(m_PeopleElement);
        
        m_PhotoElement = new PhotoListElement(1);
        listElements.add(m_PhotoElement);

        if (savedInstanceState != null) {
            for (Element_BaseList listElement : listElements) {
                listElement.restoreState(savedInstanceState);
            }
            pendingAnnounce = savedInstanceState.getBoolean(PENDING_ANNOUNCE_KEY, false);
        }

        listView.setAdapter(new ActionListAdapter(getActivity(), R.id.selection_list, listElements));

        PBUtility.LOG("selection fragment init");
        
        // in case, activity is recreated from low memory or camera or gallery
        
        m_PeopleElement.selectedUsers = SelfieBattleApplication.Instance().getSelectedUsers();
        m_PeopleElement.setUsersText();
        m_PhotoElement.setPhotoText();
        
    }

   

    private void UploadPhotoToFB() 
    {
        Session session = ParseFacebookUtils.getSession();

        List<String> permissions = session.getPermissions();
        if (!permissions.contains(PERMISSION)) 
        {
            pendingAnnounce = true;
            if(progressDialog != null )
            {
            	progressDialog.dismiss();
            	progressDialog = null;
            }
            
            if(getActivity() != null)
            {
            	((MainActivity)getActivity()).requestPublishPermissions(session,REAUTH_ACTIVITY_CODE);
            }
           
            return;
        }
        
        // Run this in a background thread so we can process the list of responses and extract errors.
        AsyncTask<Void, Void, List<Response>> task = new AsyncTask<Void, Void, List<Response>>() 
        {
        	 @Override
        	 public void onPostExecute(List<Response> citations) 
        	 {
        		 if (fileAndMinDimemsion != null) 
        			 GetPhotoAlbumnViewURLAndLikeCount( m_BT_Info.PhotoID_P1 ,  m_BT_Info.PhotoID_P2 );
        	 }
        	 

            @Override
            protected List<Response> doInBackground(Void... voids) 
            {
                

                RequestBatch requestBatch = new RequestBatch();

                //String photoStagingUri = null;

                if (m_photoUri != null) 
                {
                    try 
                    {
                        
                        
                        if (fileAndMinDimemsion != null) 
                        {
                        	// create a response callback for uploading photo
                        	Request.Callback imageCallback = new Request.Callback() 
                        	{

                                @Override
                                public void onCompleted(Response response) 
                                {
                                	                              	
                                    // Log any response error
                                    FacebookRequestError error = response.getError();
                                    if (error != null) 
                                    {                                      
                                    	PBUtility.LOG(error.getErrorMessage());
                                    	ShowCannotUploadPhoto();                                    	
                                    }
                                    else
                                    {
                                    	PBUtility.LOG(response.toString());  
                                    	
                                    	GraphObject graphObject = response.getGraphObject();
                                    	if (graphObject != null) 
               	                	 	{
	                                    	JSONObject jsonObject = graphObject.getInnerJSONObject();
	                                    	
	                                    	 try 
	            	                         {
	            	                            
	                                    		 PBUtility.LOG("id = "+ jsonObject.get("id"));	            	                               
	            	                             m_BT_Info.PhotoID_P1 = jsonObject.get("id").toString();   
	            	                             
	            	                        } 
	            	                        catch (JSONException e) 
	            	                        {
	            	                        	e.printStackTrace();
	            	                        }	  	                        
	                                    	           		         	                        		         	       
	            	                       
               	                	 	}
            		         	        
                                    }
                                }
                            };
                        	
                            Request photoUploadRequest = Request.newUploadPhotoRequest(Session.getActiveSession(),
                                            											fileAndMinDimemsion.first, imageCallback);
                            Bundle params = photoUploadRequest.getParameters();
                            params.putString("message", "#Selfie Battle via #SelfieBattle http://goo.gl/NaDjRj");
                            
                                                       
                            photoUploadRequest.setBatchEntryName("photoUpload");
                            requestBatch.add(photoUploadRequest);                            
                          
                           
                        }
                    } 
                    catch (FileNotFoundException e) 
                    {
                    	ShowCannotUploadPhoto();
                    	return null;
                    }
                }      
              
                if (fileAndMinDimemsion == null) 
                {
                	ShowCannotUploadPhoto();
                	requestBatch.add(new Request()) ;
                }
             
                return requestBatch.executeAndWait();
            }
            

           
        };

        task.execute();
    }

    
    private void ShowCannotUploadPhoto()
    {
    	if (progressDialog != null) 
        {
            progressDialog.dismiss();
            progressDialog = null;
            
        }
    	
    	String text = getString(R.string.check_internet);
        Toast toast = Toast.makeText(getActivity(), text, Toast.LENGTH_SHORT);
        toast.show();
    }
      

    private Pair<File, Integer> getImageFileAndMinDimension() 
    {
        File photoFile = null;
        String photoUriString = m_photoUri.toString();
        if (photoUriString.startsWith("file://")) 
        {
            photoFile = new File(m_photoUri.getPath());
        } 
        else if (photoUriString.startsWith("content://")) 
        {
            String [] filePath = { MediaStore.Images.Media.DATA };
            Cursor cursor = getActivity().getContentResolver().query(m_photoUri, filePath, null, null, null);
            if (cursor != null) 
            {
            	String filename = "";
            	try 
            	{
	                cursor.moveToFirst();                
	                int columnIndex = cursor.getColumnIndex(filePath[0]);
	                filename = cursor.getString(columnIndex);
            	}
                catch (Exception e) 
                {
					// TODO: handle exception
                	cursor.close();
                	return null;
				}
                cursor.close();

                photoFile = new File(filename);
            }
        }

        if (photoFile != null) 
        {
            InputStream is = null;
            try 
            {
                is = new FileInputStream(photoFile);

                // We only want to get the bounds of the image, rather than load the whole thing.
                BitmapFactory.Options options = new BitmapFactory.Options();
                options.inJustDecodeBounds = true;
                BitmapFactory.decodeStream(is, null, options);

                return new Pair<File, Integer>(photoFile, Math.min(options.outWidth, options.outHeight));
            } 
            catch (Exception e) 
            {
            	PBUtility.LOG(e.getMessage());
                return null;
                
            } 
            finally 
            {
                Utility.closeQuietly(is);
            }
        }
        return null;
    }

    /**
     * Creates a GraphObject with the following format:
     * {
     *     url: ${uri},
     *     user_generated: true
     * }
     */
   


    private void startPickerActivity(Uri data, int requestCode) {
        Intent intent = new Intent();
        intent.setData(data);
        intent.setClass(getActivity(), ActivityPicker.class);
        startActivityForResult(intent, requestCode);
    }

      

    private class PeopleListElement extends Element_BaseList 
    {

        private static final String FRIENDS_KEY = "friends";

        private List<GraphUser> selectedUsers;

        public PeopleListElement(int requestCode) 
        {
            super(getActivity().getResources().getDrawable(R.drawable.action_people),
                    getActivity().getResources().getString(R.string.action_people),
                    getActivity().getResources().getString(R.string.action_people_default),
                    requestCode);
        }

        @Override
        protected View.OnClickListener getOnClickListener() 
        {
            return new View.OnClickListener() 
            {
                @Override
                public void onClick(View view) 
                {
                	Session S = ParseFacebookUtils.getSession();
                    if (S != null && S.isOpened()) 
                    {
                        startPickerActivity(ActivityPicker.FRIEND_PICKER, getRequestCode());
                    }
                    else 
                    {
                    	SelfieBattleApplication.Instance().LogoutUser();
                    	if(getActivity() != null)
                			((MainActivity) getActivity()).showFragment(MainActivity.SPLASH);
                    }
                }
            };
        }

        @Override
        protected void onActivityResult(Intent data) 
        {
            selectedUsers = SelfieBattleApplication.Instance().getSelectedUsers();
            setUsersText();
            notifyDataChanged();
        }

        @Override
        protected void populateOGAction(OpenGraphAction action) {
            if (selectedUsers != null) {
                action.setTags(selectedUsers);
            }
        }

        @Override
        protected void onSaveInstanceState(Bundle bundle) {
            if (selectedUsers != null) {
                bundle.putByteArray(FRIENDS_KEY, getByteArray(selectedUsers));
            }
        }

        @Override
        protected boolean restoreState(Bundle savedState) {
            byte[] bytes = savedState.getByteArray(FRIENDS_KEY);
            if (bytes != null) {
                selectedUsers = restoreByteArray(bytes);
                setUsersText();
                return true;
            }
            return false;
        }

        public void setUsersText() 
        {
        	 PBUtility.LOG("setUsersText");
        	 
            String text = null;
            if (selectedUsers != null) 
            {
            	PBUtility.LOG("setUsersText 1");
            	
                if (selectedUsers.size() == 1) 
                {
                    text = String.format(getResources().getString(R.string.single_user_selected),
                            selectedUsers.get(0).getName());
                } 
                else if (selectedUsers.size() == 2)
                {
                    text = String.format(getResources().getString(R.string.two_users_selected),
                            selectedUsers.get(0).getName(), selectedUsers.get(1).getName());
                } 
                else if (selectedUsers.size() > 2) 
                {
                    text = String.format(getResources().getString(R.string.multiple_users_selected),
                            selectedUsers.get(0).getName(), (selectedUsers.size() - 1));
                }
            }
            
            if (text == null) 
            {
                text = getResources().getString(R.string.action_people_default);
            }
            setText2(text);
        }

        private byte[] getByteArray(List<GraphUser> users) 
        {
            // convert the list of GraphUsers to a list of String where each element is
            // the JSON representation of the GraphUser so it can be stored in a Bundle
            List<String> usersAsString = new ArrayList<String>(users.size());

            for (GraphUser user : users) 
            {
                usersAsString.add(user.getInnerJSONObject().toString());
            }
            try 
            {
                ByteArrayOutputStream outputStream = new ByteArrayOutputStream();
                new ObjectOutputStream(outputStream).writeObject(usersAsString);
                return outputStream.toByteArray();
            } 
            catch (IOException e)
            {
            	PBUtility.LOG("Unable to serialize users.");
            }
            return null;
        }

        private List<GraphUser> restoreByteArray(byte[] bytes) {
            try {
                @SuppressWarnings("unchecked")
                List<String> usersAsString =
                        (List<String>) (new ObjectInputStream(new ByteArrayInputStream(bytes))).readObject();
                if (usersAsString != null) {
                    List<GraphUser> users = new ArrayList<GraphUser>(usersAsString.size());
                    for (String user : usersAsString) {
                        GraphUser graphUser = GraphObject.Factory
                                .create(new JSONObject(user), GraphUser.class);
                        users.add(graphUser);
                    }
                    return users;
                }
            } 
            catch (ClassNotFoundException e) 
            {
            	PBUtility.LOG("Unable to deserialize users.");
            } 
            catch (IOException e) 
            {
            	PBUtility.LOG("Unable to deserialize users.");
            } 
            catch (JSONException e) 
            {
            	PBUtility.LOG("Unable to deserialize users.");
            }
            return null;
        }
    }

    

    private class PhotoListElement extends Element_BaseList {
        private static final int CAMERA = 0;
        private static final int GALLERY = 1;
        private static final String PHOTO_URI_KEY = "photo_uri";
        private static final String TEMP_URI_KEY = "temp_uri";
        private static final String FILE_PREFIX = "selfie_img_";
        private static final String FILE_SUFFIX = ".jpg";

        private Uri tempUri = null;

        public PhotoListElement(int requestCode) 
        {
            super(getActivity().getResources().getDrawable(R.drawable.action_photo),
                    getActivity().getResources().getString(R.string.action_photo),
                    getActivity().getResources().getString(R.string.action_photo_default),
                    requestCode);
            //m_photoUri = null;
        }

        @Override
        protected View.OnClickListener getOnClickListener() {
            return new View.OnClickListener() {
                @Override
                public void onClick(View view) {
                    showPhotoChoice();
                }
            };
        }

        @Override
        protected void onActivityResult(Intent data) 
        {        	
        	PBUtility.LOG("photo selected");
            if (tempUri != null) 
            {
            	m_photoUri = tempUri;
            } 
            else if (data != null) 
            {
            	m_photoUri = data.getData();
            }
            setPhotoText();
        }

        @Override
        protected void populateOGAction(OpenGraphAction action) {
        }

        @Override
        public void onSaveInstanceState(Bundle bundle) {
            if (m_photoUri != null) {
                bundle.putParcelable(PHOTO_URI_KEY, m_photoUri);
            }
            if (tempUri != null) {
                bundle.putParcelable(TEMP_URI_KEY, m_photoUri);
            }
        }

        @Override
        public boolean restoreState(Bundle savedState) {
        	m_photoUri = savedState.getParcelable(PHOTO_URI_KEY);
            tempUri = savedState.getParcelable(TEMP_URI_KEY);
            setPhotoText();
            return true;
        }

        private void showPhotoChoice() 
        {
        	if(getActivity() != null)
        	{
        		((MainActivity)getActivity()).SetLocale();
        		
        	}
        	
            AlertDialog.Builder builder = new AlertDialog.Builder(getActivity());
            CharSequence camera = getResources().getString(R.string.action_photo_camera);
            CharSequence gallery = getResources().getString(R.string.action_photo_gallery);
            builder.setCancelable(true).
                    setItems(new CharSequence[] {camera, gallery}, new DialogInterface.OnClickListener()
                    {
                        @Override
                        public void onClick(DialogInterface dialogInterface, int i) 
                        {
                            if (i == CAMERA) 
                            {                            	
                                startCameraActivity();
                            } 
                            else if (i == GALLERY) 
                            {                            	
                                startGalleryActivity();
                            }
                        }
                    });
            builder.show();
        }

        public void setPhotoText() 
        {
        	PBUtility.LOG("setPhotoText 1");
            if (m_photoUri == null) 
            {
            	PBUtility.LOG("setPhotoText 2");
                setText2(getResources().getString(R.string.action_photo_default));
            } 
            else 
            {
            	PBUtility.LOG("setPhotoText 3");
                setText2(getResources().getString(R.string.action_photo_ready));
            }
        }

        private void startCameraActivity() 
        {
            Intent intent = new Intent(MediaStore.ACTION_IMAGE_CAPTURE);
            tempUri = getTempUri();
            if (tempUri != null) {
                intent.putExtra(MediaStore.EXTRA_OUTPUT, tempUri);
            }
            startActivityForResult(intent, getRequestCode());
        }

        private void startGalleryActivity() 
        {
            tempUri = null;
            Intent intent = new Intent(Intent.ACTION_GET_CONTENT);
            intent.setType("image/*");
            String selectPicture = getResources().getString(R.string.select_picture);
            startActivityForResult(Intent.createChooser(intent, selectPicture), getRequestCode());
        }

        private Uri getTempUri() {
            String imgFileName = FILE_PREFIX + System.currentTimeMillis() + FILE_SUFFIX;

            // Note: on an emulator, you might need to create the "Pictures" directory in /mnt/sdcard first
            //       % adb shell
            //       % mkdir /mnt/sdcard/Pictures
            File image = new File(
                    Environment.getExternalStoragePublicDirectory(Environment.DIRECTORY_PICTURES), imgFileName);
            return Uri.fromFile(image);
        }
    }

    private class ActionListAdapter extends ArrayAdapter<Element_BaseList> {
        private List<Element_BaseList> listElements;

        public ActionListAdapter(Context context, int resourceId, List<Element_BaseList> listElements) {
            super(context, resourceId, listElements);
            this.listElements = listElements;
            for (int i = 0; i < listElements.size(); i++) {
                listElements.get(i).setAdapter(this);
            }
        }

        @Override
        public View getView(int position, View convertView, ViewGroup parent) {
            View view = convertView;
            if (view == null) {
                LayoutInflater inflater =
                        (LayoutInflater) getActivity().getSystemService(Context.LAYOUT_INFLATER_SERVICE);
                view = inflater.inflate(R.layout.listitem, null);
            }

            Element_BaseList listElement = listElements.get(position);
            if (listElement != null) {
                view.setOnClickListener(listElement.getOnClickListener());
                ImageView icon = (ImageView) view.findViewById(R.id.icon);
                TextView text1 = (TextView) view.findViewById(R.id.text1);
                TextView text2 = (TextView) view.findViewById(R.id.text2);
                if (icon != null) {
                    icon.setImageDrawable(listElement.getIcon());
                }
                if (text1 != null) {
                    text1.setText(listElement.getText1());
                }
                if (text2 != null) {
                    text2.setText(listElement.getText2());
                }
            }
            return view;
        }

    }
    
    private void ShowCannotCreateBattle(int StrId)
    {
    	if(getActivity() == null)
    		return;
    	
    	AlertDialog.Builder dlgAlert  = new AlertDialog.Builder(getActivity());
		dlgAlert.setMessage(getActivity().getResources().getString(StrId));
		//dlgAlert.setTitle("App Title");
		dlgAlert.setPositiveButton("OK", null);
		dlgAlert.setCancelable(true);
		dlgAlert.setPositiveButton("Ok",
			        			    new DialogInterface.OnClickListener() 
			        				{
			        			        public void onClick(DialogInterface dialog, int which)
			        			        {
			        			          //dismiss the dialog  
			        			        }
			        			    });
		if(progressDialog != null)
			progressDialog.dismiss();
		dlgAlert.create().show();
    }
    
    
    
    private void handleAnnounce() 
    {
        pendingAnnounce = false;
        Session session = ParseFacebookUtils.getSession();
        
        // if we have a session, then use the graph API to directly publish, otherwise use
        // the native open graph share dialog.
        //if (session != null && session.isOpened()) {
        //    handleGraphApiAnnounce();
        //} else {
        //    handleNativeShareAnnounce();
        //}
        
        
        if (session != null && session.isOpened())
        {
        	// Show a progress dialog because sometimes the requests can take a while.
            progressDialog = ProgressDialog.show(getActivity(), "",  getActivity().getResources().getString(R.string.progress_dialog_text), true);

	        
///------------------	    
	        String PlayerID2 =  "";
	        List<GraphUser> Users = SelfieBattleApplication.Instance().getSelectedUsers();
	        if( Users != null && Users.size() > 0)
	        {
	        	GraphUser SelectedUser = Users.get(0);    
	        	if(SelectedUser != null)
	        	{
	        		PlayerID2 = SelectedUser.getId();	        		
	        	}
	        	
	        }	        
        	else
        	{
        		ShowCannotCreateBattle(R.string.pleasechooseopponent);
        		return;
        	}
	        
	        if(m_photoUri == null)
	        {
	        	ShowCannotCreateBattle(R.string.pleasechoosephoto);
	        	return;
	        }
	        
	        fileAndMinDimemsion = getImageFileAndMinDimension();
	        if(fileAndMinDimemsion == null)
	        {
	        	ShowCannotCreateBattle(R.string.photocannotuse);
	        	return;
	        }
	        
	        
	        String fqlQuery = "SELECT  object_id FROM photo WHERE aid in (SELECT aid FROM album WHERE owner = '" + PlayerID2 + "' AND type = 'profile') LIMIT 0,1";
	        Bundle params = new Bundle();
	        params.putString("q", fqlQuery);

	        Request request = new Request(session, 
	            "/fql", 
	            params, 
	            HttpMethod.GET, 
	            new Request.Callback()
	        { 
	                public void onCompleted(Response response) 
	                {
	                	 GraphObject graphObject = response.getGraphObject();	                	
	                	
	                	 if (graphObject != null) 
	                	 {
	                		 if(m_BT_Info == null)
	                         {
	                        	m_BT_Info = new BattleInfo();
	                        	m_BT_Info.PhotoID_P1 = "";
	                        	m_BT_Info.PhotoID_P2 = "";
	                        	m_BT_Info.Player_ID1 = "";
	                        	m_BT_Info.PlayerName_P1 = "";
	                        	m_BT_Info.PlayerName_P2 = "";
	                         }
                		 
	                         JSONObject jsonObject = graphObject.getInnerJSONObject();
	                         
	                         try 
	                         {
	                             JSONArray array = jsonObject.getJSONArray("data");
	                             for (int i = 0; i < array.length(); i++) 
	                             {
	                                 JSONObject object = (JSONObject) array.get(i);
	                                 m_BT_Info.PhotoID_P2 = object.get("object_id").toString();                                
	                             }
	                        } 
	                        catch (JSONException e) 
	                        {
	                        	e.printStackTrace();
	                        	if (progressDialog != null) 
                                {
                                    progressDialog.dismiss();
                                    progressDialog = null;
                                }
	                        }	                         
	                         
	                       
	                        // player 1
	                        m_BT_Info.Player_ID1 = SelfieBattleApplication.Instance().GetFBID();                      
		                	
		                	// player 2
		                	GraphUser SelectedUser = SelfieBattleApplication.Instance().getSelectedUsers().get(0);        	 
		                	m_BT_Info.Player_ID2 = SelectedUser.getId();
		        	        			                	
		        	        m_BT_Info.PlayerName_P1 = userNameView.getText().toString();
		        	        m_BT_Info.PlayerName_P2 = SelectedUser.getName();     
		                	
		        	        if(m_BT_Info.PhotoID_P2.isEmpty())
		        	        {
		        	        	ShowCannotCreateBattle(R.string.cannotattack);
		        	        }
		        	        else
		        	        {
		        	        	UploadPhotoToFB();
		        	        }
	                        
	                        //DataManager.UpdateWinnerID("UQcyr65MpK", "549483876" , "549483876", "100004546325654");
	                        PBUtility.LOG("date: " + System.currentTimeMillis()); 
	                        
	                	 }
	                	 else
	                	 {
	                		 if (progressDialog != null) 
                             {
                                 progressDialog.dismiss();
                                 progressDialog = null;
                             }
	                	 }
	            }
	        });
	        
	        
	        Request.executeBatchAsync(request);

        }
    }
    
    
    
    private void GetPhotoAlbumnViewURLAndLikeCount(String ID1, String ID2)
    {
    	Session session = Session.getActiveSession();
    	
    	 if (session != null && session.isOpened())
         {}
    	 else
    	 {
    		 return;
    	 }
    	 
    	 PBUtility.LOG("Getting Albumn view " + ID1 + " , " + ID2 );
    	
    	String fqlQuery = "SELECT src, like_info FROM photo WHERE object_id = '" + ID1 + "' OR object_id = '" + ID2 + "' ";
        Bundle params = new Bundle();
        params.putString("q", fqlQuery);

        Request request = new Request(session, 
            "/fql", 
            params, 
            HttpMethod.GET, 
            new Request.Callback()
        { 
                public void onCompleted(Response response) 
                {
                	
                	 GraphObject graphObject = response.getGraphObject();
	               	 String AlbumnViewURL1 = "";
	               	 String AlbumnViewURL2 = "";
	               	 int LIKE_COUNT_P2 = 0;
	               	 
	               	 if (graphObject != null) 
	               	 {
	                        JSONObject jsonObject = graphObject.getInnerJSONObject();
	                        
	                        try 
	                        {
	                            JSONArray array = jsonObject.getJSONArray("data");
	                            for (int i = 0; i < array.length(); i++) 
	                            {
	                                JSONObject object = (JSONObject) array.get(i);
	                                PBUtility.LOG("url = "+ object.get("src"));
	                                
	                                if(i == 0)
	                                {
	                                	AlbumnViewURL1 = object.get("src").toString();
	                                }
	                                else if( i == 1)
	                                {
	                                	AlbumnViewURL2 = object.get("src").toString();
	                                	
	                                	JSONObject jsonObjectLIKE = object.getJSONObject("like_info");
	                                	LIKE_COUNT_P2 = jsonObjectLIKE.getInt("like_count");
	                                }
	                                
	                                PBUtility.LOG(AlbumnViewURL1);
	                                PBUtility.LOG(AlbumnViewURL2);
	                                PBUtility.LOG("LIKE COUNT: " + LIKE_COUNT_P2);
	                                
	                               	 
	                            }
	                       } 
	                       catch (JSONException e) 
	                       {
	                    	   e.printStackTrace();
	                    	   if (progressDialog != null) 
                               {
                                   progressDialog.dismiss();
                                   progressDialog = null;
                               }
	                       }
	                        
	                        
	                       
		         	        
		         	        DataManager.SaveBattle(m_BT_Info.Player_ID1 , m_BT_Info.Player_ID2, m_BT_Info.PhotoID_P1, m_BT_Info.PhotoID_P2 ,
		         	        						LIKE_COUNT_P2, AlbumnViewURL1, AlbumnViewURL2,
		         	        						m_BT_Info.PlayerName_P1, m_BT_Info.PlayerName_P2);
		         	        
		         	       m_photoUri = null;
		         	       if(m_PeopleElement != null)
		         	    	   m_PhotoElement.setPhotoText();
		         	       
		         	       if(m_PeopleElement != null)
		         	       {
		         	    	   SelfieBattleApplication.Instance().setSelectedUsers(null);
		         	    	  m_PeopleElement.setText2(getResources().getString(R.string.action_people_default));
		         	       }
		         	        
		         	       if (progressDialog != null) 
                           {
                               progressDialog.dismiss();
                               progressDialog = null;
                           }
		         	       
		         	       SendFBInvite(m_BT_Info.Player_ID2, "Take selfie and let's play", true);
		         	        
		         	       
	                }
	               	else
	               	{
	               		if (progressDialog != null) 
                        {
                            progressDialog.dismiss();
                            progressDialog = null;
                        }
	               	}
                }
                
        });
        
        Request.executeBatchAsync(request);
    }
    
    
    private void SendFBInvite(String FBID, String Message, boolean AskToInformAllies)
    {
    	Bundle params = new Bundle();
    	
    	// Uncomment following link once uploaded on Google Play for deep linking
    	// params.putString("link", "https://play.google.com/store/apps/details?id=com.facebook.android.friendsmash");
    	//  params.putString("title", "Send a Request");
    	//    params.putString("data",
    	//        "{\"badge_of_awesomeness\":\"1\"," +
    	//        "\"social_karma\":\"5\"}");  // any additional data
    	
    	
    	params.putString("message", Message);

    	// 2. Optionally provide a 'to' param to direct the request at a specific user
    	params.putString("to", FBID);  
    	showDialogWithoutNotificationBar("apprequests", params, AskToInformAllies);
    }
    
 // Show a dialog (feed or request) without a notification bar (i.e. full screen)
 	private void showDialogWithoutNotificationBar(String action, Bundle params, final boolean AskToInformAllies) 
 	{
 		if( Session.getActiveSession() == null)
 		{
 			PBUtility.LOG("Session is not open to send FB invites!");
 			return;
 		}
 		
 		// Create the dialog
 		WebDialog dialog = new WebDialog.Builder(getActivity(), Session.getActiveSession() , action, params).setOnCompleteListener(
 				new WebDialog.OnCompleteListener() 
 		{		
 			
			@Override
			public void onComplete(Bundle values, FacebookException error) 
			{
				// TODO Auto-generated method stub
				if(error != null && error.getMessage() != null)
					PBUtility.LOG( error.getMessage());
 				
				if(AskToInformAllies)
				{
					WantToBringAllies();
				}
				else
				{
					if(getActivity() != null)
					{
						String text = "Your Photo is uploaded to your timeline. Please don't delete within 24 hours or you will lose the battle";
	        	        Toast toast = Toast.makeText(getActivity(), text, Toast.LENGTH_SHORT);
	        	        toast.show();
					}
        	        
					ShowFragmentBattles();
				}
			}
 			
 			
 		}).build();
 		
 		// Hide the notification bar and resize to full screen
 		Window dialog_window = dialog.getWindow();
     	dialog_window.setFlags(WindowManager.LayoutParams.FLAG_FULLSCREEN, WindowManager.LayoutParams.FLAG_FULLSCREEN);     	
     	     	
     	// Show the dialog
     	dialog.show();
 	}
 	
 	private void ShowFragmentBattles()
 	{
 		MainActivity Ac  = (MainActivity)getActivity();
 		if(Ac != null)
 		{
 			Ac.showFragment( MainActivity.BATTLES);
 		}
 	}
 	
 	
 	private void WantToBringAllies()
 	{
 		if(getActivity() == null)
 			return;
 		
 		 		
	 	DialogInterface.OnClickListener dialogClickListener = new DialogInterface.OnClickListener() 
		{
		    @Override
		    public void onClick(DialogInterface dialog, int which) 
		    {
		        switch (which)
		        {
		        case DialogInterface.BUTTON_POSITIVE:
		            //Yes button clicked
		        	BringPotentialAllies();
		            break;
	
		        case DialogInterface.BUTTON_NEGATIVE:
		        	ShowFragmentBattles();
		            break;
		        }
		    }
		};
	
		AlertDialog.Builder builder = new AlertDialog.Builder(getActivity());
		builder.setTitle("Inform Allies");
		builder.setIcon(getResources().getDrawable( R.drawable.fblike ));
		
		String Msg = getResources().getString(R.string.inform_allies);
		
		builder.setMessage(Msg).setPositiveButton("Yes", dialogClickListener)
		    .setNegativeButton("No", dialogClickListener).show();
 	
 	}
 	
 	
 	private void BringPotentialAllies()
    {
    
    	Session session = ParseFacebookUtils.getSession();
    	if(session.isClosed())
    		return;
    	
    	
    	
    	String fqlQuery = "SELECT user_id FROM like WHERE object_id in (  SELECT  object_id FROM photo WHERE aid in (SELECT aid FROM album WHERE owner = me() AND type = 'profile') LIMIT 0,3 ) LIMIT 0,29";
        Bundle params = new Bundle();
        params.putString("q", fqlQuery);

        Request request = new Request(session, 
            "/fql", 
            params, 
            HttpMethod.GET, 
            new Request.Callback()
        { 
        	        	
            public void onCompleted(Response response) 
            {
            	 GraphObject graphObject = response.getGraphObject();
            	 
            	 if(progressDialog != null)
            	 {
            		 progressDialog.hide();
            		 progressDialog = null;
            	 }
            	
            	 if (graphObject != null) 
            	 {
            		 String[] PotentialAllies = null;            		 
                     JSONObject jsonObject = graphObject.getInnerJSONObject();
                     String UID_List = "";
                     
                     try 
                     {
                         JSONArray array = jsonObject.getJSONArray("data");
                         
                         PotentialAllies = new String[array.length()];
                         
                         for (int i = 0; i < array.length(); i++) 
                         {
                             JSONObject object = (JSONObject) array.get(i);
                             PotentialAllies[i] = object.get("user_id").toString();           
                             
                         }
                         
                         for(int i = 0; i < PotentialAllies.length; i++)
                         {        	
                     		if(PotentialAllies[i].isEmpty() == false)
                     		{
                 				UID_List += PotentialAllies[i];
                 				if( i <  (PotentialAllies.length) -1 )
                 				{
                 					UID_List += ",";
                 				}
                     		}                     		        	
                         }
                         
                         if(UID_List.isEmpty() == false)
                        	 SendFBInvite(UID_List, "Will you be my ally?", false);
                    } 
                    catch (JSONException e) 
                    {
                    	
                    }	   
            	 }
                	
            }
        });
        
        
        Request.executeBatchAsync(request);
        progressDialog = ProgressDialog.show(getActivity(), "",  getActivity().getResources().getString(R.string.lookpotentialallies), true);
    }
}